const { exec } = require('child_process');
const { program } = require('commander');
const path = require('path');
const fs = require('fs-extra');
const inquirer = require('inquirer');
const sysType = require('os').type().toLowerCase();
const TemplateList = [
  'fitment', // 装企
  'furniture' // 家居模板
];
const envList = [
  'uat',
  'stg',
  'prd',
];

function chooseEnv() {
  return new Promise((resolve) => {
    inquirer
      .prompt([
        {
          type: 'list',
          name: 'proEnv',
          message: '请选择打包环境',
          choices: envList,
        },
      ])
      .then((answers) => {
        resolve(answers.proEnv);
      });
  });
}
function chooseTemplate() {
  return new Promise((resolve) => {
    inquirer
      .prompt([
        {
          type: 'list',
          name: 'proTemplate',
          message: '请选择打包模板',
          choices: TemplateList,
        },
      ])
      .then((answers) => {
        resolve(answers.proTemplate);
      });
  });
}

function unibuild(env) {
  return new Promise((resolve) => {
    let command;
    if (sysType.indexOf('win') > -1) {
      command = env.NODE_ENV === 'production'
        ? 'node node_modules/@dcloudio/vite-plugin-uni/bin/uni.js build -p mp-weixin'
        : 'node node_modules/@dcloudio/vite-plugin-uni/bin/uni.js -p mp-weixin';
    } else {
      command = env.NODE_ENV === 'production'
        ? 'node node_modules/.bin/uni build uni -p mp-weixin'
        : 'node node_modules/.bin/uni -p mp-weixin';
    }
    const subprocess = exec(command, {
      env,
    }, (error) => {
      if (error) {
        console.error('执行的错误', error);
        return;
      }
      resolve();
    });
    subprocess.stderr.on('data', (err) => {
      console.error(err);
    });
    subprocess.stdout.on('data', (data) => {
      console.log(data);
    });
  });
}
function initWxConfig(env) {
  const configPath = path.join(__dirname, 'project.config.json');
  const config = fs.readJSONSync(configPath);
  config.miniprogramRoot = `dist/${env.NODE_ENV === 'production' ? 'build' : 'dev'}/mp-weixin/`;
  fs.outputJsonSync(configPath, config, { spaces: 2 });
  console.log('\nproject.config.json已生成');
}
const main = async() => {
  const proEnv = await chooseEnv();
  const proTemplate = await chooseTemplate();
  program.version('0.0.1');
  program
    .option('-b, --build', '构建项目');
  program.parse();

  const env = {
    PRO_ENV: proEnv,
    NODE_ENV: program.build ? 'production' : 'development',
    UNI_PLATFORM: 'mp-weixin',
    PRO_TEMPLATE: proTemplate
  };
  initWxConfig(env);
  unibuild(env);
};
main();
